package com.example.common.utils;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

/**
 * HTTP工具栏
 * 
 * 
 * @version $Id: HttpClientUtil.java, v 0.1 2015-5-22 下午4:29:27 YiKe Exp $
 */
@Slf4j
public class HttpClientUtil {

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     * 
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, List<NameValuePair> params) {
        if (log.isInfoEnabled()) {
            StringBuffer sb = new StringBuffer(url).append("?");
            for (int i = 0, length = params == null ? 0 : params.size(); i < length; i++) {
                if (i > 0) {
                    sb.append("&");
                }
                sb.append(params.get(i).getName()).append("=").append(params.get(i).getValue());
            }
            log.info("发送请求，URL：" + sb.toString());
        }
        String result = "";
        try {
            CloseableHttpClient httpClient = create(url);

            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            }
            // 关闭连接,释放资源
            httpClient.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            log.info("响应请求，RESULT：" + result);
        }
        return result;
    }

    /**
     * post xml 文件到目标服务器
     *
     * @param url
     * @param xmlData
     * @return
     */
    public static String postXml(String url, String xmlData) {
        if (log.isInfoEnabled()) {
            StringBuffer sb = new StringBuffer(url).append("?").append(xmlData);
            log.info("发送请求，URL：" + sb.toString());
        }
        String result = "";
        try {
            CloseableHttpClient httpClient = create(url);

            HttpPost httpPost = new HttpPost(url);
            StringEntity xmlEntity = new StringEntity(xmlData, "utf-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(xmlEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            }
            // 关闭连接,释放资源
            httpClient.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            log.info("响应请求，RESULT：" + result);
        }
        return result;
    }

    /**
     * 创建一个 CloseableHttpClient 对象
     * 
     * @param url
     * @return
     */
    private static CloseableHttpClient create(String url) {
        try {
            if (StringUtils.startsWithIgnoreCase(url, "https")) {
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    // 信任所有
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                }).build();
                SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
                CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
                return httpClient;
            }
            // 创建默认的httpClient实例.
            CloseableHttpClient httpClient = HttpClients.createDefault();
            return httpClient;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }



    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl,
                                         String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
                    .openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            // log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            // log.error("https request error:{}", e);
        }
        return jsonObject;
    }

}
